import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:go_router/go_router.dart';
import '../../providers/comic_reader_provider.dart';

class ComicReaderScreen extends ConsumerStatefulWidget {
  final String chapterId;
  final String? comicId;
  final List<String>? chapterIds; // 所有章节ID列表，用于导航

  const ComicReaderScreen({
    super.key,
    required this.chapterId,
    this.comicId,
    this.chapterIds,
  });

  @override
  ConsumerState<ComicReaderScreen> createState() => _ComicReaderScreenState();
}

class _ComicReaderScreenState extends ConsumerState<ComicReaderScreen> {
  late ScrollController _scrollController;
  late PageController _pageController;
  bool _isVerticalScroll = true; // 默认垂直滚动模式

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _pageController = PageController();

    // 设置全屏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);

    // 初始化阅读器，加载当前章节及相邻章节
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.chapterIds != null) {
        ref
            .read(comicReaderProvider.notifier)
            .initializeReader(widget.chapterId, widget.chapterIds!);
      }
    });

    // 监听滚动，动态加载更多章节
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    final readerState = ref.read(comicReaderProvider);
    if (readerState.allImages.isEmpty) return;

    // 计算当前可见的图片索引
    final scrollOffset = _scrollController.offset;
    final viewportHeight = _scrollController.position.viewportDimension;

    // 这里可以根据滚动位置更新当前图片索引
    // 具体实现取决于你的图片布局
  }

  Widget _buildVerticalScroll(ComicReaderState state) {
    final allImages = state.allImages ?? <ChapterImageInfo>[];
    if (allImages.isEmpty) {
      return const Center(
        child: Text('Loading...', style: TextStyle(color: Colors.grey)),
      );
    }

    return ListView.builder(
      controller: _scrollController,
      itemCount: state.allImages.length,
      itemBuilder: (context, index) {
        final imageInfo = state.allImages[index];

        return Column(
          children: [
            // 章节分隔符（当是新章节的第一张图片时显示）
            if (imageInfo.imageIndex == 0 && index > 0)
              _buildChapterDivider(imageInfo),

            // 图片
            Container(
              margin: const EdgeInsets.only(bottom: 2),
              child: _buildImageWidget(imageInfo.imageUrl, index),
            ),
          ],
        );
      },
    );
  }

  Widget _buildChapterDivider(ChapterImageInfo imageInfo) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 20),
      margin: const EdgeInsets.symmetric(vertical: 8),
      decoration: BoxDecoration(
        color: Colors.deepPurple.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        imageInfo.chapterTitle,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: Colors.deepPurple,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget _buildHorizontalPages(ComicReaderState state) {
    if (state.allImages.isEmpty) {
      return const Center(
        child: Text('Loading...', style: TextStyle(color: Colors.grey)),
      );
    }

    return PageView.builder(
      controller: _pageController,
      onPageChanged: (index) {
        ref.read(comicReaderProvider.notifier).updateImageIndex(index);
      },
      itemCount: state.allImages.length,
      itemBuilder: (context, index) {
        final imageInfo = state.allImages[index];
        return _buildImageWidget(imageInfo.imageUrl, index);
      },
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _pageController.dispose();
    // 恢复系统UI
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
    super.dispose();
  }

  // void _onScroll() {
  //   if (_scrollController.position.pixels >=
  //       _scrollController.position.maxScrollExtent * 0.8) {
  //     _preloadNextChapter();
  //   }
  // }

  void _preloadNextChapter() {
    if (widget.chapterIds != null) {
      final currentIndex = widget.chapterIds!.indexOf(widget.chapterId);
      if (currentIndex >= 0 && currentIndex < widget.chapterIds!.length - 1) {
        final nextChapterId = widget.chapterIds![currentIndex + 1];
        ref
            .read(comicReaderProvider.notifier)
            .preloadNextChapter(nextChapterId);
      }
    }
  }

  void _goToNextChapter() {
    if (widget.chapterIds != null) {
      final currentIndex = widget.chapterIds!.indexOf(widget.chapterId);
      if (currentIndex >= 0 && currentIndex < widget.chapterIds!.length - 1) {
        final nextChapterId = widget.chapterIds![currentIndex + 1];
        // 使用provider在当前页面切换到下一章节，而不是跳转页面
        ref
            .read(comicReaderProvider.notifier)
            .switchToNextChapter(nextChapterId);
      }
    }
  }

  void _goToPreviousChapter() {
    if (widget.chapterIds != null) {
      final currentIndex = widget.chapterIds!.indexOf(widget.chapterId);
      if (currentIndex > 0) {
        final previousChapterId = widget.chapterIds![currentIndex - 1];
        // 使用provider在当前页面切换到上一章节，而不是跳转页面
        ref
            .read(comicReaderProvider.notifier)
            .switchToPreviousChapter(previousChapterId);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final readerState = ref.watch(comicReaderProvider);

    return Scaffold(
      backgroundColor: readerState.isDarkMode ? Colors.black : Colors.white,
      body: Stack(
        children: [
          // 主要内容区域
          _buildMainContent(readerState),

          // 顶部导航栏
          if (readerState.showUI) _buildTopBar(readerState),

          // 底部工具栏
          if (readerState.showUI) _buildBottomBar(readerState),

          // 加载指示器
          if (readerState.isLoading) _buildLoadingIndicator(),

          // 错误提示
          if (readerState.error != null) _buildErrorWidget(readerState.error!),
        ],
      ),
    );
  }

  Widget _buildMainContent(ComicReaderState state) {
    if (state.imageUrls.isEmpty) {
      return const Center(
        child:
            Text('No images available', style: TextStyle(color: Colors.grey)),
      );
    }

    return GestureDetector(
      onTap: () {
        ref.read(comicReaderProvider.notifier).toggleUI();
      },
      child: _isVerticalScroll
          ? _buildVerticalScroll(state)
          : _buildHorizontalPages(state),
    );
  }

  // Widget _buildVerticalScroll(ComicReaderState state) {
  //   return ListView.builder(
  //     controller: _scrollController,
  //     itemCount: state.imageUrls.length + 1, // +1 for next chapter button
  //     itemBuilder: (context, index) {
  //       if (index == state.imageUrls.length) {
  //         return _buildNextChapterButton();
  //       }

  //       return Container(
  //         margin: const EdgeInsets.only(bottom: 2),
  //         child: _buildImageWidget(state.imageUrls[index], index),
  //       );
  //     },
  //   );
  // }

  // Widget _buildHorizontalPages(ComicReaderState state) {
  //   return PageView.builder(
  //     controller: _pageController,
  //     onPageChanged: (index) {
  //       ref.read(comicReaderProvider.notifier).updateImageIndex(index);
  //       if (index == state.imageUrls.length - 1) {
  //         _preloadNextChapter();
  //       }
  //     },
  //     itemCount: state.imageUrls.length,
  //     itemBuilder: (context, index) {
  //       return _buildImageWidget(state.imageUrls[index], index);
  //     },
  //   );
  // }

  Widget _buildImageWidget(String imageUrl, int index) {
    return InteractiveViewer(
      panEnabled: true,
      boundaryMargin: const EdgeInsets.all(20),
      minScale: 0.5,
      maxScale: 3.0,
      child: CachedNetworkImage(
        imageUrl: imageUrl,
        fit: BoxFit.fitWidth,
        placeholder: (context, url) => Container(
          height: 200,
          color: Colors.grey[200],
          child: const Center(
            child: CircularProgressIndicator(
              color: Color(0xFF6C5CE7),
            ),
          ),
        ),
        errorWidget: (context, url, error) => Container(
          height: 200,
          color: Colors.grey[200],
          child: const Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.broken_image, color: Colors.grey, size: 50),
              SizedBox(height: 8),
              Text('Image failed to load',
                  style: TextStyle(color: Colors.grey)),
            ],
          ),
        ),
        // 启用内存缓存和磁盘缓存
        memCacheHeight: 800,
        memCacheWidth: 600,
      ),
    );
  }

  Widget _buildNextChapterButton() {
    return Container(
      height: 100,
      margin: const EdgeInsets.all(16),
      child: ElevatedButton(
        onPressed: _goToNextChapter,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF6C5CE7),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: const Text(
          'Next Chapter',
          style: TextStyle(color: Colors.white, fontSize: 16),
        ),
      ),
    );
  }

  Widget _buildTopBar(ComicReaderState state) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              (state.isDarkMode ? Colors.black : Colors.white).withOpacity(0.9),
              Colors.transparent,
            ],
          ),
        ),
        child: SafeArea(
          child: AppBar(
            backgroundColor: Colors.transparent,
            foregroundColor: state.isDarkMode ? Colors.white : Colors.black,
            elevation: 0,
            title: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  state.currentChapter?.title ?? 'Loading...',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: state.isDarkMode ? Colors.white : Colors.black,
                  ),
                ),
                Text(
                  'Chapter ${state.currentChapter?.chapterNum ?? ''}',
                  style: TextStyle(
                    fontSize: 12,
                    color: (state.isDarkMode ? Colors.white : Colors.black)
                        .withOpacity(0.7),
                  ),
                ),
              ],
            ),
            actions: [
              IconButton(
                icon: Icon(_isVerticalScroll
                    ? Icons.view_carousel
                    : Icons.view_stream),
                onPressed: () {
                  setState(() {
                    _isVerticalScroll = !_isVerticalScroll;
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBottomBar(ComicReaderState state) {
    final progress = state.imageUrls.isNotEmpty
        ? (state.currentImageIndex + 1) / state.imageUrls.length
        : 0.0;

    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
            colors: [
              (state.isDarkMode ? Colors.black : Colors.white).withOpacity(0.9),
              Colors.transparent,
            ],
          ),
        ),
        child: SafeArea(
          child: Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 进度条
                Row(
                  children: [
                    Text(
                      '${state.currentImageIndex + 1}',
                      style: TextStyle(
                        color: state.isDarkMode ? Colors.white : Colors.black,
                        fontSize: 12,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: LinearProgressIndicator(
                        value: progress,
                        backgroundColor: Colors.grey[300],
                        valueColor: const AlwaysStoppedAnimation<Color>(
                            Color(0xFF6C5CE7)),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '${state.imageUrls.length}',
                      style: TextStyle(
                        color: state.isDarkMode ? Colors.white : Colors.black,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                // 工具栏按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildToolButton(
                      icon: Icons.skip_previous,
                      onPressed: _goToPreviousChapter,
                      isDarkMode: state.isDarkMode,
                    ),
                    _buildToolButton(
                      icon: Icons.list,
                      onPressed: () => _showChapterList(context),
                      isDarkMode: state.isDarkMode,
                    ),
                    _buildToolButton(
                      icon:
                          state.isDarkMode ? Icons.light_mode : Icons.dark_mode,
                      onPressed: () => ref
                          .read(comicReaderProvider.notifier)
                          .toggleDarkMode(),
                      isDarkMode: state.isDarkMode,
                    ),
                    _buildToolButton(
                      icon: Icons.settings,
                      onPressed: () => _showSettings(context),
                      isDarkMode: state.isDarkMode,
                    ),
                    _buildToolButton(
                      icon: Icons.skip_next,
                      onPressed: _goToNextChapter,
                      isDarkMode: state.isDarkMode,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildToolButton({
    required IconData icon,
    required VoidCallback onPressed,
    required bool isDarkMode,
  }) {
    return IconButton(
      icon: Icon(
        icon,
        color: isDarkMode ? Colors.white : Colors.black,
      ),
      onPressed: onPressed,
      style: IconButton.styleFrom(
        backgroundColor:
            (isDarkMode ? Colors.white : Colors.black).withOpacity(0.1),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return Container(
      color: Colors.black54,
      child: const Center(
        child: CircularProgressIndicator(
          color: Color(0xFF6C5CE7),
        ),
      ),
    );
  }

  Widget _buildErrorWidget(String error) {
    return Container(
      color: Colors.black54,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: Colors.red,
              size: 64,
            ),
            const SizedBox(height: 16),
            Text(
              error,
              style: const TextStyle(color: Colors.white),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                ref.read(comicReaderProvider.notifier).clearError();
                ref
                    .read(comicReaderProvider.notifier)
                    .loadChapter(widget.chapterId);
              },
              child: const Text('Retry'),
            ),
          ],
        ),
      ),
    );
  }

  void _showChapterList(BuildContext context) {
    // 显示章节列表弹窗
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        height: 400,
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            const Text(
              'Chapter List',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: ListView.builder(
                itemCount: widget.chapterIds?.length ?? 0,
                itemBuilder: (context, index) {
                  final chapterId = widget.chapterIds![index];
                  final isCurrentChapter = chapterId == widget.chapterId;

                  return ListTile(
                    title: Text('Chapter ${index + 1}'),
                    trailing: isCurrentChapter
                        ? const Icon(Icons.play_arrow, color: Color(0xFF6C5CE7))
                        : null,
                    onTap: () {
                      Navigator.pop(context);
                      if (!isCurrentChapter) {
                        context.pushReplacement('/reader/$chapterId');
                      }
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showSettings(BuildContext context) {
    // 显示设置弹窗
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              'Reading Settings',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            SwitchListTile(
              title: const Text('Vertical Scroll'),
              value: _isVerticalScroll,
              onChanged: (value) {
                setState(() {
                  _isVerticalScroll = value;
                });
                Navigator.pop(context);
              },
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }
}
